from django.shortcuts import render, HttpResponse, get_object_or_404, HttpResponseRedirect, reverse
from django.utils import timezone
from django.core.cache import cache, caches
# Create your views here.
from .models import Category, Article, Tags, Comment
from .forms import CommentForm
from  accountt.models import UserInfo

def index(request):

    article_list = Article.objects.all()
    context = {'article_list':article_list}
    return render(request, 'blog/index.html', context)


def category(request, slug):

    category = get_object_or_404(Category, slug=slug)
    return render(request, 'blog/category_list.html', locals())


def article(request, article_id):

    article = get_object_or_404(Article, id=article_id)
    content_count = len(str(article.content))


    per_article = Article.objects.filter(id__lt=article.id).first()
    next_article = Article.objects.filter(id__gt=article.id).order_by('id').first()
   

    if request.method != "POST":

        form = CommentForm()
    else:

        form = CommentForm(data=request.POST)

        if form.is_valid():

            user = UserInfo.objects.get(author=request.user)
            new_article = form.save(commit=False)
            new_article.author = user
            new_article.article = article
            new_article.save()
            return HttpResponseRedirect(reverse('blog:article', args=[article_id]))
    return render(request, 'blog/article.html', locals())


def blog_get_dates(request, year, month):
    blog_dates = Article.objects.filter(add_date__year=year, add_date__month=month)
    return render(request, 'blog/dates.html', locals())


def blog_get_tags(request, tag_id):
    tag = get_object_or_404(Tags, id=tag_id)
    return render(request, 'blog/tags.html', locals())